package com.smasher.doc.ui;

import android.Manifest;
import android.content.ContentResolver;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.util.Log;
import android.view.View;
import android.widget.Toast;

import androidx.activity.EdgeToEdge;
import androidx.activity.result.ActivityResult;
import androidx.activity.result.ActivityResultLauncher;
import androidx.activity.result.IntentSenderRequest;
import androidx.activity.result.contract.ActivityResultContracts;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.content.ContextCompat;
import androidx.core.graphics.Insets;
import androidx.core.view.ViewCompat;
import androidx.core.view.WindowInsetsCompat;

import com.smasher.doc.R;
import com.smasher.doc.util.CopyUtil;

import java.io.File;

public class HomeActivity extends AppCompatActivity {


    public static final String TAG = "Main";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EdgeToEdge.enable(this);
        setContentView(R.layout.activity_main);
        ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.main), (v, insets) -> {
            Insets systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars());
            v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom);
            return insets;
        });
    }

    public void convertSimple(View view) {
        Intent intent = new Intent(this, DocActivity.class);
        startActivity(intent);
    }

    public void requestPermission(View view) {
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.S) {
            mLauncher.launch(Manifest.permission.WRITE_EXTERNAL_STORAGE);
        }

    }

    public void transform(View view) {
        handleWriteExternalStorage("newSSS.docx");
    }

    /**
     * test.docx
     * 将沙盒中的文件 保存到外部存储区域
     */
    public void handleWriteExternalStorage(String fullName) {
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.S) {
            int result = ContextCompat.checkSelfPermission(
                    this, Manifest.permission.WRITE_EXTERNAL_STORAGE);
            if (result != PackageManager.PERMISSION_GRANTED) {
                Toast.makeText(this, "请先获取权限", Toast.LENGTH_LONG).show();
                return;
            }
        }

        File sandFile = new File(getExternalFilesDir("Doc") + File.separator + fullName);
        if (!sandFile.exists()) {
            Toast.makeText(this, "目标文件不存在", Toast.LENGTH_LONG).show();
            return;
        }
        Uri externalUri = executeUri(fullName);
        FileCopyTask task = new FileCopyTask(this, sandFile.getAbsolutePath(), externalUri);
        new Thread(task).start();
    }

    private void showToastIntelligent(String msg) {
        Toast.makeText(this, msg, Toast.LENGTH_LONG).show();
    }

    private Uri executeUri(String fullName) {
        Uri externalUri;
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.Q) {
            File externalFile = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS);
            File destFile = new File(externalFile + File.separator + fullName);
            externalUri = Uri.fromFile(destFile);
        } else {
            ContentResolver resolver = getContentResolver();
            ContentValues values = new ContentValues();
            values.put(MediaStore.Downloads.DISPLAY_NAME, fullName);
            values.put(MediaStore.Downloads.RELATIVE_PATH, Environment.DIRECTORY_DOWNLOADS);//保存路径
            Uri uri = MediaStore.Files.getContentUri("external");
            externalUri = resolver.insert(uri, values);
        }
        return externalUri;
    }

    class FileCopyTask implements Runnable {

        private final String mSrcPath;
        private final Uri externalUri;
        private final ContentResolver contentResolver;
        private StringBuilder resultBuilder;

        public FileCopyTask(
                Context context,
                String mSrcPath,
                Uri externalUri
        ) {
            this.contentResolver = context.getContentResolver();
            this.mSrcPath = mSrcPath;
            this.externalUri = externalUri;
        }

        @Override
        public void run() {
            String downloadPath =
                    Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS).getAbsolutePath();
            boolean ret =
                    CopyUtil.copySandFileToExternalUri(contentResolver, mSrcPath, externalUri);
            resultBuilder = new StringBuilder().append("从沙盒")
                    .append(mSrcPath)
                    .append("中拷贝文件到外部存储")
                    .append(downloadPath)
                    .append(", 结果= ")
                    .append(ret);
            runOnUiThread(() -> {
                Log.i(TAG, resultBuilder.toString());
                showToastIntelligent(resultBuilder.toString());
            });
        }
    }

    private final ActivityResultLauncher<String> mLauncher = registerForActivityResult(
            new ActivityResultContracts.RequestPermission(), result -> {
                showToastIntelligent("权限获取结果：" + result);
            });

    private final ActivityResultLauncher<IntentSenderRequest> mSenderLauncher = registerForActivityResult(
            new ActivityResultContracts.StartIntentSenderForResult(), result -> {
                String resultValue = ActivityResult.resultCodeToString(result.getResultCode());
                showToastIntelligent("权限获取结果：" + resultValue);

            });
}